// pages/orgDetail/orgDetail.js
const app = getApp();
const util = require("../../../utils/util.js");
const qiniu = require("../../../utils/qiniu.min.js");
import Toast from '../../..//dist/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgpopup: false,
    id: '',
    detail: {},
    permission: {},
    permission1: false,
    search: {
      pageNumber: 1,
      pageSize: 18,
      totalPages: 0,
      orgId: '',
    },
    loginShow: false,
    login: false,
    phone: false,
    phoneshow: false,
  },
  login() {
    if (this.data.login) {
      this.toggle('phoneshow', true)
      this.selectComponent('#phone').showClose()
    } else {
      this.toggle('loginShow', true)
      this.selectComponent('#login').showClose()
    }
  },
  loginClose() {
    this.toggle('loginShow', false)
  },
  toggleToast(e) {
    console.log(e.detail)
    if (!e.detail.loginShow) {
      this.toggle('loginShow', false)
    }
    this.refreshData()
  },
  toggleToast1(e) {
    console.log(e.detail)
    if (!e.detail.phoneshow) {
      this.toggle('phoneshow', false)
    }
    this.refreshData()
  },
  org(e) {
    console.log('org')
    var dataset = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/orgHome/orgHome?id=' + dataset.orgid
    })
  },
  typeClose() {
    this.toggle("typeShow", false);
  },
  onClose: function () {
    this.toggle("show", false);
  },
  imgpopup(e) {
    var that = this
    var type = e.currentTarget.dataset.type
    if (type == 0) {
      that.toggle('imgpopup', true);
    } else {
      that.toggle('imgpopup', false);
    }
  },
  // 更换封面
  changeBg: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type
    if (type == 0) {
      wx.navigateTo({
        url: '/pages/gallery/gallery?id=' + that.data.id,
      })
    } else if (type == 1) {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['camera'],
        success(res) {
          // that.saveData();
          const avatar = res.tempFilePaths[0];
          wx.navigateTo({
            url: '../upload/upload?src=' + avatar + '&id=' + that.data.id
          })
        }
      })
    } else if (type == 2) {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album'],
        success(res) {
          // that.saveData();
          const avatar = res.tempFilePaths[0];
          wx.navigateTo({
            url: '../upload/upload?src=' + avatar + '&id=' + that.data.id
          })
        }
      })
    }
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  detail: function () {
    var that = this;
    app.req({
      // url: "orgmini/org/detail",
      url: "orgmini/org/newGetOrgInfo",
      data: {
        orgId: that.data.id
      },
      success: function (res) {
        if (200 == res.code) {
          var detail = res.data
          that.toggle("detail", detail);
          if (detail.orgTypeName == '其他') {
            wx.setNavigationBarTitle({
              title: '风采展示'
            })
          } else {
            wx.setNavigationBarTitle({
              title: detail.orgTypeName + '风采'
            })
          }
          var permission = {};
          var detail = res.data;
          permission.isAdmin = detail.isOrg * 1 == 5 || (detail.isOrg * 1 == 1 && detail.isAdmin == 1);
          permission.isManager = detail.isOrg * 1 == 5;
          var userPermission = res.data.managerAuthList;
          // console.log('管理员权限列表', userPermission)
          if (userPermission && userPermission.length > 0) {
            for (let i of userPermission) {
              permission[i] = 1;
              if (userPermission[i] == 11) {
                that.toggle("permission1", true)
              }
            }
            permission.hasItem = 1;
          }
          that.toggle("permission", permission);
        }
      }
    });
  },
  // 获取图片列表
  getOrgStylePictureList(add){
    var that = this;
    app.req({
      url:"orgmini/org/getOrgStylePictureList",
      method:"post",
      data: that.data.search,
      success(res){
        if(res.code == 200){
          var picList = [];
          var picList = add ? that.data.picList.concat(res.data.rows) : res.data.rows;
          // for (var item of picList){
          //   item.choose = false;
          // }
          that.toggle("picList", picList);
          that.toggle("search.totalPages", res.data.totalPages);
          if (that.data.delete && !that.data.picList.length){
            that.toggle("delete", false);
          }
        }
      }
    })
  },
  openDelete(){
    this.toggle("delete", !this.data.delete);
  },
  uploadImg(){
    var that = this;
    if (this.data.delete){
      if (!this.data.ids.length){
        wx.showToast({
          icon:"none",
          title: '您未选择图片',
        })
      }else{
        wx.showModal({
          title: '',
          content: '删除' + this.data.ids.length + "张照片",
          success(res) {
            if (res.confirm) {
              app.req({
                url: "orgmini/org/deleteOrgStylePicture",
                method: "post",
                data: {
                  "ids": that.data.ids
                },
                success(res) {
                  if (res.code == 200) {
                    that.toggle("search.pageNumber", 1);
                    that.toggle("search.pageSize", 18);
                    that.toggle("search.totalPages",0);
                    that.getOrgStylePictureList();
                    that.toggle("ids",[])
                    wx.showToast({
                      icon:"none",
                      title: '删除成功',
                    })
                  }
                }
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }else{
      console.log("上传图片");
      app.getQiNiuToken(function (res) {
        var countnum = 9;
        var qiniuconfig = res;
        let timestamp = new Date().getTime();
        wx.chooseImage({
          count: countnum,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          success: function (res) {
            const filepathArray = res.tempFilePaths
            for (let i = 0; i < filepathArray.length; i++) {
              qiniu.upload(filepathArray[i], res => {
                console.log("图片地址", res.imageURL)
                // that.setData({
                //   urlList: that.data.urlList.concat([res.imageURL]),
                //   picList: that.data.picList.concat([{
                //       choose: false,
                //       pictureUrl: res.imageURL,
                //       isDelFlag:1
                //     }] ),
                // })
                app.req({
                  url: "orgmini/org/addOrgStylePictureList",
                  method: "post",
                  data: {
                    "orgId": that.data.id,
                    "urlList": [res.imageURL]
                  },
                  success(res) {
                    if (res.code == 200) {
                      wx.showToast({
                        icon: "none",
                        title: '上传成功',
                      })
                    }
                    that.getOrgStylePictureList();
                  }
                })
              }, (error) => {
                console.log('上传error' + error)
              }, {
                  uploadURL: 'https://upload.qiniup.com',
                  region: 'ECN',
                  domain: qiniuconfig.qiniuDomain,
                  uptoken: qiniuconfig.upToken,
                })
            }
          }
        })
      });
    }
  },
  delDelete(e){
    var index = e.currentTarget.dataset.index;
    console.log(index);
    var temp_str = "picList[" + index + "].choose";
    this.setData({
      [temp_str]: !this.data.picList[index].choose
    })
    var ids = [];
    for (var item of this.data.picList){
      if (item.choose){
        ids.push(item.id);
      }
    }
    this.toggle("ids",ids);
  },
  openImg(e){
    var index = e.currentTarget.dataset.index;
    var imgArr = [];
    console.log('图片地址', this.data.picList)
    for (var i = 0; i < this.data.picList.length; i++) {
      imgArr.push(this.data.picList[i].pictureUrl);
    };
    console.log(imgArr);
    wx.previewImage({
      current: imgArr[index],     //当前图片地址
      urls: imgArr,               //所有要预览的图片的地址集合 数组形式
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) {},
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // var id = '06b0692609d711ea995200163e05ff66';
    this.toggle("search.orgId", options.id);
    this.toggle("id", options.id);
    this.getOrgStylePictureList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  refreshData: function () {
    var that = this;
    wx.getSetting({
      success(res) {
        that.detail();
        // if (!res.authSetting['scope.userInfo'] || wx.getStorageSync('uid') == '') {
        if ( wx.getStorageSync('uid') == '') {
          that.toggle("login", false);
        } else {
          that.toggle("login", true);
          var phone = wx.getStorageSync("phone")
          if (phone == '') {
            that.toggle("phone", true);
          } else {
            that.toggle("phone", false);
          }

        }
      },
    })

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getlistFriend();
    this.refreshData();
    this.toggle("imgpopup", false);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.toggle("search.pageNumber", 1);
    this.refreshData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    var search = that.data.search;
    if (search.totalPages > search.pageNumber) {
      that.toggle("search.pageNumber", search.pageNumber + 1);
      that.getOrgStylePictureList(true);
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {

  }
})